package chpt11;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class MultiThreadTCPServer {
    public static void main(String[] args) throws IOException{
    	int port = 9000;
		try(ServerSocket server = new ServerSocket(port)){
			while(true){
				Socket socket = server.accept();
				Thread workThread = new Thread(new MsgHandler(socket));
				workThread.start();
			}
		}
    }
}
class MsgHandler implements Runnable {
    private Socket socket;
    public MsgHandler(Socket socket) {
        this.socket = socket;
    }
    public void run() {
        try(BufferedReader reader = new BufferedReader(
        		new InputStreamReader(socket.getInputStream()));
            PrintWriter writer = new PrintWriter(
            		socket.getOutputStream());) {
            while (true) {
                String line = reader.readLine();
                if (line.equals("bye"))
                    break;
                writer.println(line);
                writer.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


